<template>
	<cl-drawer
		ref="drawer"
		:props="{
			title: '新增派单',
			size: '750px',
			appendToBody: true
		}"
		show-confirm
		confirm-text="提交派单"
		@close="reset"
		@confirm="submit"
		:saving="saving"
	>
		<el-form ref="form" :model="form" :rules="rules" label-position="top" :disabled="saving">
			<el-form-item label="基本信息">
				<el-card shadow="never">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="客户姓名" prop="cus_name">
								<el-input
									v-model="form.cus_name"
									placeholder="请输入客户姓名"
									:maxlength="6"
									:disabled="disabledCus"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="联系电话" prop="cus_mobile" required>
								<el-input
									v-model="form.cus_mobile"
									placeholder="请输入联系电话"
									:maxlength="11"
									:disabled="disabledCus"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="所属地区" prop="region">
								<cl-cascader
									v-model="form.region"
									:options="addressLevel"
									placeholder="请选择所属地区"
									style="width: 100%"
									@change="regionChange"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="是否指定事业部派单" prop="is_cus_biz" required>
								<el-radio-group v-model="form.is_cus_biz" @change="isCusBizChange">
									<el-radio :label="false">否</el-radio>
									<el-radio :label="true">是</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="form.is_cus_biz">
							<el-form-item label="事业部" prop="appointed_biz_id">
								<cl-select
									v-model="form.appointed_biz_id"
									style="width: 100%"
									@change="cusBizChange"
									filterable
								>
									<el-option
										v-for="item in business"
										:key="item.biz_id"
										:label="item.biz_name"
										:value="item.biz_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
						<!-- <el-col :span="12">
							<el-form-item label="是否指定到店时间" prop="is_arrival" required>
								<el-radio-group v-model="form.is_arrival" @change="isArrivalChange">
									<el-radio :label="false">否</el-radio>
									<el-radio :label="true">是</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col> -->
						<el-col :span="12">
							<el-form-item label="到店时间" prop="start_time">
								<!-- <cl-date-picker
									v-model="form.start_time"
									type="datetime"
									placeholder="选择日期时间 (大于此刻两小时) "
									default-time="12:00:00"
									format="yyyy-MM-dd HH:mm"
									value-format="yyyy-MM-dd HH:mm"
									style="width: 100%"
									:picker-options="pickerStar"
									minTime
								/> -->
								<el-row type="flex">
									<cl-date-picker
										v-model="form.start_time"
										type="date"
										placeholder="选择日期"
										:picker-options="pickerOptionstime"
										value-format="yyyy-MM-dd"
										@change="selectTime"
									/>
									<div class="plr-1">-</div>
									<el-time-select
										v-model="form.clock_time"
										:picker-options="appointDateOptions"
										placeholder="选择时间"
										style="width: 175px"
									/>
								</el-row>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item prop="received_proportion">
								<template #label>
									分润比例<span class="tips">
										(接单商户将获得派出客户实际消费总额的{{
											form.received_proportion
										}}%)
									</span>
								</template>
								<el-input
									v-model.number="form.received_proportion"
									@blur="form.received_proportion = Number($event.target.value)"
									placeholder="例如30%"
									oninput="value=value.replace(/[^\d]/g,'')"
									maxlength="3"
									type="number"
									class="clear-number-input"
								>
									<template slot="append">%</template>
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="定金金额" prop="deposit">
								<cl-select
									v-model="form.deposit"
									placeholder="请选择定金金额"
									clearable
									style="width: 100%"
									v-if="depositData.length"
								>
									<el-option
										v-for="item in depositData"
										:key="item.id"
										:label="item.deposit + ' 元'"
										:value="item.deposit"
									/>
								</cl-select>
								<el-input
									v-else
									v-model="form.deposit"
									@blur="form.deposit = Number($event.target.value)"
									oninput="value=value.replace(/[^\d^\.]/g,'')"
									placeholder="请输入定金金额"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="是否参与结算" prop="deposit_ispay" required>
								<el-radio-group v-model="form.deposit_ispay">
									<el-radio :label="2">否</el-radio>
									<el-radio :label="1">是</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row>
				</el-card>
			</el-form-item>
			<el-form-item label="待做服务" required>
				<el-card shadow="never">
					<el-form-item prop="serviceList">
						<el-table border :data="form.serviceList">
							<el-table-column
								prop="si_name"
								label="服务名称"
								min-width="200"
								align="center"
							/>
							<!-- <el-table-column label="赠送" width="60" align="center">
							<template slot-scope="{ row }">
								<el-checkbox v-model="row.giving" />
							</template>
						</el-table-column> -->
							<!-- <el-table-column label="体验" width="60" align="center">
							<template slot-scope="{ row }">
								<el-checkbox v-model="row.experience" />
							</template>
						</el-table-column> -->
							<el-table-column label="数量" align="center" width="60">
								<template> x1 </template>
							</el-table-column>
							<el-table-column
								label="预约售价"
								prop="price"
								width="150"
								align="center"
							>
								<template slot-scope="{ row }">
									<!-- <div class="flex flex-align-center">
										￥
										<el-input-number
											v-model="row.price"
											placeholder="请输入预约售价"
											:min="0"
											style="flex:1"
										/>
									</div> -->
									<el-input
										v-model="row.price"
										oninput="value=value.replace(/[^\d^\.]/g,'')"
										placeholder="请输入预约售价"
										@blur="row.price = $event.target.value"
									>
										<template slot="prepend">￥</template>
									</el-input>
									<!-- ￥{{ row.price }} -->
								</template>
							</el-table-column>
							<el-table-column label="操作" width="80" align="center">
								<template slot-scope="{ $index: index }">
									<el-button @click="deleteServe(index)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-form-item>
					<div class="flex flex-justify-center pt-2">
						<el-tooltip
							content="请指定事业部进行派单"
							placement="top"
							:disabled="
								(business.length > 1 && !!form.appointed_biz_id) ||
									business.length == 1
							"
						>
							<cl-choice-service
								v-model="form.serviceList"
								:biz_id="form.appointed_biz_id"
								:disabled="business.length > 1 && !form.appointed_biz_id"
								@confirm="serviceConfirm"
							/>
						</el-tooltip>
					</div>
				</el-card>
			</el-form-item>
			<el-form-item label="派单备注" prop="remark">
				<el-input
					v-model="form.remark"
					type="textarea"
					placeholder="请填写派单备注"
					:rows="3"
				/>
			</el-form-item>
		</el-form>
	</cl-drawer>
</template>
<script>
import { validate } from "@/utils/validate";
import threeLevel from "@/assets/countryLevel3";
import dayjs from "dayjs";
export default {
	name: "cl-dispatch-drawer",
	props: {
		disabledCus: {
			type: Boolean,
			default: false
		}
	},
	data() {
		const mobileValidator = (rule, value, callback) => {
			if (this.disabledCus) {
				return callback();
			}
			if (!value) {
				return callback(new Error("请输入联系电话"));
			}
			if (!validate.mobile.test(value)) {
				return callback(new Error("联系电话格式不正确"));
			}
			return callback();
		};
		return {
			addressLevel: threeLevel,
			form: {
				cus_id: "", // 客户ID
				cus_biz_id: "", //客户所在事业部ID
				cus_name: "", // 客户名称
				cus_mobile: "", // 联系电话
				region: [], //所属地区
				province: "", //省
				city: "", //市
				area: "", //区
				is_cus_biz: false, //是否指定事业部派单
				appointed_biz_id: "", // 事业部
				is_arrival: false, // 是否指定到店时间
				start_time: "", // 到店时间
				clock_time: "",
				received_proportion: 30, // 分润比例
				deposit: "", // 定金金额
				deposit_ispay: 2, // 定金是否参与折算
				serviceList: [], // 可选服务项目列表
				remark: "", // 派单备注
				market_price: "" //预约服务总价
			},
			rules: {
				cus_name: [{ required: true, message: "请输入客户姓名" }],
				cus_mobile: [{ required: true, validator: mobileValidator }],
				region: [{ required: true, message: "请选择所属地区" }],
				appointed_biz_id: [{ required: true, message: "请选择事业部" }],
				start_time: [{ required: true, message: "请选择到店时间" }],
				received_proportion: [
					{ required: true, message: "请输入分润比例" },
					{ min: 0, max: 100, type: "number", message: "分润比例不能大于100" }
				],
				deposit: [{ pattern: validate.price, message: "定金格式不正确" }],
				serviceList: [{ type: "array", required: true, message: "请选择预约项目" }]
			},
			pickerOptionstime: {
				disabledDate(time) {
					return time.getTime() <= new Date() - 24 * 60 * 60 * 1000;
				}
			},
			appointDateOptions: {
				start: "08:00",
				step: "00:30",
				end: "23:30",
				minTime: "00:00"
			},
			popoverVisible: false,
			//定金数据
			depositData: [],
			saving: false
		};
	},
	methods: {
		open(data = {}) {
			this.$refs.drawer.create();
			console.log("派单1", data);
			// this.form.appointed_biz_id = this.getCurrBiz();
			Object.keys(this.form).forEach(key => {
				data[key] && (this.form[key] = data[key]);
			});
			let minTime = dayjs().format("HH:mm");
			this.appointDateOptions.minTime = minTime;
			console.log("派单2", this.form);
		},
		reset() {
			this.saving = false;
			this.$resetFields(this.form);
			this.$refs.form.resetFields();
		},
		close() {
			this.$refs.drawer.close();
			this.reset();
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				const { serviceList, clock_time, start_time, ...args } = this.form;
				this.saving = true;
				let serviceName = []; //待服务项目名称
				let serviceid = []; //待服务项目id
				let serviceObj = []; //待服务金额数量
				let serviveAll = 0; //服务总价
				serviceList.forEach(v => {
					serviceName.push(v.si_name);
					serviceid.push(v.si_id);
					serviveAll += Number(v.price);
					serviceObj.push({
						num: 1,
						price: v.price
					});
				});
				let form = {
					...args,
					wait_service_id: serviceid.join(","), //待做服务id
					wait_service: serviceName.join(","), //待做服务
					wait_service_items: JSON.stringify(serviceObj), //待做服务数据
					market_price: serviveAll //预约服务总价
				};
				form.start_time = start_time + " " + clock_time;
				form.appointed_biz_id = form.is_cus_biz ? form.appointed_biz_id : ''

				this.$delete(form, "region");
				this.$delete(form, "is_cus_biz");
				this.$delete(form, "is_arrival");

				if (this.disabledCus) {
					this.$delete(form, "cus_mobile");
				}
				await this.$service.cluecus.add(form).done(() => {
					this.saving = false;
				});
				this.$message.success("操作成功");
				this.reset();
				this.close();
				this.$emit("confirm");
			});
		},
		async getDetail(id) {
			const data = await this.$service.cluecus.singleDetail(id);
			Object.keys(this.form).forEach(key => {
				data[key] && (this.form[key] = data[key]);
			});
		},
		cusBizChange() {
			this.form.serviceList = [];
			this.depositData = [];
			this.form.deposit = "";
			this.getDepositlist();
		},
		// 获取定金列表
		async getDepositlist() {
			const { appointed_biz_id } = this.form;
			const data = await this.$service.public.depositlist(appointed_biz_id);
			this.depositData = data;
		},
		//地区
		regionChange(v) {
			this.form.province = v[0]; //省
			this.form.city = v[1]; //市
			this.form.area = v[2]; //区
		},
		// 是否指定事业部派单
		isCusBizChange() {
			this.form.appointed_biz_id = "";
			this.depositData = [];
			this.form.serviceList = [];
			this.form.deposit = "";
			if (this.business.length <= 1) {
				this.confirm("当前只有一个事业部").finally(() => {
					this.form.is_cus_biz = false;
				});
			}
		},
		selectTime(e) {
			let date = dayjs().format("YYYY-MM-DD");
			this.form.clock_time = "";
			if (dayjs(e).isAfter(date)) {
				this.appointDateOptions.minTime = "00:00";
			} else {
				this.appointDateOptions.minTime = dayjs().format("HH:mm");
			}
		},
		// 是否指定到店时间
		isArrivalChange() {
			this.form.start_time = "";
		},
		serviceConfirm(val) {
			this.form.serviceList = val;
			this.$refs.form.validateField("serviceList");
		},
		deleteServe(index) {
			this.form.serviceList.splice(index, 1);
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep {
	.el-col {
		min-height: 78px;
	}
}
</style>
